local blaze = require "blaze"
local base = blaze.event

local M = {}

local records = setmetatable({}, { __mode = "k" } ) -- <handler, {event_name1, event_name2, ...}>

local function record(handler, event_name)
    local r = records[handler]
    if not r then
        -- 一条记录都没有，只记事件名
        records[handler] = event_name
    elseif type(r) == "string" then
        -- 有一条记录，转为数组
        records[handler] = { r, event_name }
    else
        -- 有多条记录，追加到数组末尾
        table.insert(r, event_name)
    end
end

function M.on(event_name, handler, once)
    record(handler, event_name)
    base.on(event_name, handler, once)
end

function M.release()
    for handler, r in pairs(records) do
        if type(r) == "string" then
            base.off(r, handler)
        else
            for _, event_name in ipairs(r) do
                base.off(event_name, handler)
            end
        end
    end
end

local function make(name)
    return base(name);
end

return setmetatable(M, {__index = base, __call = make})